'use strict';
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const Service = require('egg').Service;

class NameService extends Service {
    async init() {
        const Name = this.ctx.model.Name;
        await Name.sync({ alter: true });

        const Rank = this.ctx.model.Rank;
        await Rank.sync({ alter: true });
        
        const Vote = this.ctx.model.Vote;
        await Vote.sync({ alter: true });

        const nameCount = await Name.count();
        if (nameCount > 0) {
            return;
        }

        const chars = '一七三上下不专且世丘业丛东丝丞两严中丰临丸丹为主举乃久义之乐乔乙九也习乡书予争二于云互五井亘亚亢交亥亦产亨享京亭亮亲亳人亿什仁今介从仑仓仔仕付仟代令仪仰仲任仿伉伍伎伏众优伙会传伦伧估伴伶伸位住佐佑何余作佰佴佶佻使例侍侗侣侦侨侯俏俐俑俗保俞信俦俨俭修俯俱俸倌倍倏候倚倜倡倬值倾允元充兆先光兑党入全关兴其具典兹养兼冉册再冠冬冰决况冶冷净准凉凌几凡凫列则初利别力功加务励勋匀化北十千升午卉协南卢卫印却历厉厘原又及友双发叙古句另只召可台史右号司名向君吟启吾呈告员和唤图均坚坤坦坪垂城埔处备复夏夕外多夜大天太央夷夸夹奂奇奈奉奋契奔奕奚如委姿威娄娱子孔字存孚孜季学孪宁宇安宋完宏宓宗宙宛宜实审宣宥宪宴宸容宾寸寻导封将小少尔尖尘尚尝尤尧尹尼局层居屈届屏展屯山屹岁岂岩岭岱岳岸峡峥峦峰峻川州左巧巨巩己已巾市布帆师希帖帛帜帝带席年幸幻幼幽广庄序应庚度延廷开弁异弈弋引弘弛弥弦归录形彦彼往征径待律徒心必忆忱念忻忽怀态思怡恒恩恭息恳恺悌悟悦戋成或战户才托执扬扶承技择括拾持指挥振换支攸故效敖文方於旨旬时旷昀昂昆昊明易昔昕昙昭昱昶显晁晃晋晏晓晔晖晚晟曰曲曳更有朋服朔朗未本札术朴机权杉杏材束杭杰杳杷杼松板极析枕林枚果枫枳柏某柑染柚柜柠柬柯柳栖栩株核格栾桉桓桔桠桢桥桦桨梆梧欧武殊段殷水永汀汇汉汐汕汛江池沃沅沐沪河治沾泉泊泓泛泞泠波泮泯泰泱泳泸泽洁洄洋洛浣浦浩浪海涌涛涣灼灿炅炎炜炽烁烈烛烨牧玖玮玺玻珀珂珲甫甬甸町画畅界畔益盎知矩石研砚砝示礼社祀祁祈祉祖祝神祠祥祯禹禺离禾秉秋种科秦秩积究穹空突立竖站竞竹竺竿笈笏笑笔笫米粉系紊素索紧纠红约级纪纬纭纯纱纲纵纶纷纹纺纽线练组绅细织终绍绎经绒结绕绘绚绛络统绢绣绥继网罗罡美羽羿考而耐耸耿聂肃肖肩肪肯育肴胖胡胤胥胧能脉臣自臬至致舍舟航般舱艮良艺艾节芋芍芎芒芜芥芦芮芯芷芹苇苋苍苎苏苑苒苓苗苟若英苷苹苻茁茂范茅茗茜茨茫茯茱茳茵茸荀荃荆荇荏荐荔荚荞荟荠荣荥荧荪荫药荷荻莅莆莓莛莜莞莫莱获莹虔虹行衍衣表衲衷衿袅袖被西要见观规视览觉觊角言訇计订认让训议讯记讲许论设访评识词诏译诒试诗诘诚话诞询诣诤详诩语诰诲请诸诺读调谅谆谈谊谷贝贞责质贯贲贴贵贸费贺贻资赤赴赶起足身躬车轨轩轮轰轶轸轻轼辂较辛辰边辽达迁迅过迈迎运近还进远连迟迢迤迦迪迫迭述迹送适选逊透逐递逖通速造逢逦邑邢那邦邬邰邱邴邵邸邹郁郊郎郏郗郜郡部郴都酌配酒采里重金釜钉钊钏钜钟钦钧钭钮钰钱钲钿铁铃铄铎长门闪问闰闲间闵闻闽阁阅阜队阡阮阳阴阵阶阿附际陆陈陌降限院陪陵陶雨青非韧音顶项顺须顼顾顿颁颂预风飒飞饰饶首马驭驰驱驹驻驾驿骅骆骋验骏高鱼鸟鸣麦齐龙';
        const records = [];
        for(let i=0; i<chars.length; i++) {
            records.push({ char:chars[i]});
        }
       
        await Name.bulkCreate(records);
        console.log('done===============');
    }

    async random() {
        const chars = await this.ctx.model.Name.findAll({
            order: [
              Sequelize.fn('RANDOM'),
            ],
            limit: Math.random() > 0.8 ? 1 : 2
          });
        let ret = '黄';
        console.log(chars.length);
        for(let i=0;i<chars.length;i++){
            ret = ret + chars[i].char;
        }
        return ret;
    }

    async remove(char) {
        await this.ctx.model.Name.destroy({
            where : {char}
          });
    }

    async getRanks() {
        const ranks = await this.ctx.model.Rank.findAll({
            order: [
                ['vote', 'DESC'],
            ],
            where: {
                vote: {
                    [Op.gt]: 0,
                }
            },
            limit: 10
        });
        return ranks;
    }

    async getPersons(name) {
        const votes = await this.ctx.model.Vote.findAll({
            where:{
                name,
                vote:{
                    [Op.gt]: 0,
                }
            }
        });
        if(votes.length == 0) {
            return '';
        }

        const titleSet = new Set();
        for(let i=0;i<votes.length;i++) {
            titleSet.add(votes[i].title);
        }

        const titles = Array.from(titleSet);
        let ret = '';
        let max = Math.min(titles.length, 3);
        for(let i = 0;i<max; i++) {
            ret += titles[i];
            if(i < max-1) {
                ret += '、';
            }
        }
        if(titles.length > 3) {
            ret += '等'+ (titles.length - 3) +'人';
        }
        
        return ret;
    }

    async getRemainCount() {
        const ret = await this.ctx.model.Name.count();
        return ret;
    }

    async vote(name, title, score) {
        title = title || '神秘人';
        const Vote = this.ctx.model.Vote;
        await Vote.create({
            name,title,vote:score
        });

        const Rank = this.ctx.model.Rank;
        const rank = await Rank.findOne({
            where: {name}
        });

        if (!rank) {
            console.log('排行不存在');
            await Rank.create({
                name,
                vote:score
            });
            return;
        }

        console.log('排行存在');
        rank.vote = rank.vote + score;
        await rank.save();
    }
}

module.exports = NameService;
